package org.lanplay.server;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import org.apache.wicket.Page;
import org.apache.wicket.authroles.authentication.AbstractAuthenticatedWebSession;
import org.apache.wicket.authroles.authentication.AuthenticatedWebApplication;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.request.cycle.AbstractRequestCycleListener;
import org.apache.wicket.request.cycle.RequestCycle;
import org.lanplay.server.dao.UserDao;
import org.lanplay.server.model.User;
import org.lanplay.server.pages.ManualLoginPage;
import org.lanplay.server.pages.WelcomePage;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Provider;
import com.google.inject.persist.Transactional;

public class LanPlayApplication extends AuthenticatedWebApplication {

	@Inject
	private UserDao userDao;

	@Inject
	private Injector injector;

	@Inject
	private Provider<EntityManager> emp;

	@Override
	public Class<? extends Page> getHomePage() {
		return WelcomePage.class;
	}

	@Override
	protected Class<? extends AbstractAuthenticatedWebSession> getWebSessionClass() {
		return LanPlaySession.class;
	}

	@Override
	protected Class<? extends WebPage> getSignInPageClass() {

		return ManualLoginPage.class;
	}

	protected UserDao getUserDao() {
		return userDao;
	}

	public Injector getInjector() {
		return injector;
	}

	@Override
	protected void init() {
		super.init();
		getRequestCycleListeners().add(new AbstractRequestCycleListener() {
			@Override
			public void onBeginRequest(RequestCycle cycle) {
				emp.get().getTransaction().begin();
			}

			@Override
			public void onEndRequest(RequestCycle cycle) {
				EntityTransaction tx = emp.get().getTransaction();
				if (tx.isActive()) {
					if (tx.getRollbackOnly()) {
						tx.rollback();
					} else {
						tx.commit();
					}
				}
			}
		});
	}

	@Transactional
	public User createUserWithKey(String key) {
		User user = new User();
		user.setKey(key);
		userDao.save(user);
		return user;
	}

}
